package generics;

//: generics/InstantiateGenericType.java
import static net.mindview.util.Print.*;

import java.lang.reflect.Constructor;

class ClassAsFactory<T> {
  T x;
  public ClassAsFactory(Class<T> kind) {
    try {
      x = kind.newInstance();
    } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }
  public T newInstance(Class<T> type) throws Exception{
	 Constructor con =  type.getConstructor(String.class);
	 return (T)con.newInstance("a");
  }
}

class Employee {
	public Employee(){};
}	
class Employee2{
	public Employee2(){}
	public Employee2(String str){System.out.println("string constructor");}
}	


public class InstantiateGenericType {
  public static void main(String[] args) {
    ClassAsFactory<Employee> fe =
      new ClassAsFactory<Employee>(Employee.class);
    print("ClassAsFactory<Employee> succeeded");
    	 ClassAsFactory<Employee2> fe2 =
    	      new ClassAsFactory<Employee2>(Employee2.class);
    	 print("type reflect no exception");
		try {
			fe2.newInstance(Employee2.class);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
    try {
      ClassAsFactory<Integer> fi =
        new ClassAsFactory<Integer>(Integer.class);
    } catch(Exception e) {
      print("ClassAsFactory<Integer> failed");
    }
  }
} /* Output:
ClassAsFactory<Employee> succeeded
ClassAsFactory<Integer> failed
*///:~
